package customview.ike.com.customviewproject.glide;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.util.ContentLengthInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpCodec;

/**
 * @author:ike
 * @function: okHttp fetcher
 * @creat time:17:56 2018/2/12
 **/

public class OkHttpFetcher implements DataFetcher<InputStream> {
    private OkHttpClient okHttpClient;
    private GlideUrl url;
    private InputStream inputStream;
    private volatile boolean isCancelled;
    private ResponseBody body;

    public OkHttpFetcher(OkHttpClient okHttpClient, GlideUrl url) {
        this.okHttpClient = okHttpClient;
        this.url = url;
    }

    @Override
    public InputStream loadData(Priority priority) throws Exception {
        //开始图片网络请求
        Request.Builder builder = new Request.Builder().url(url.toStringUrl());
        for (Map.Entry<String, String> headerEntry : url.getHeaders().entrySet()) {
            builder.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
        Request request = builder.build();
        if (isCancelled) {
            return null;
        }
        Response response = okHttpClient.newCall(request).execute();
        if (!response.isSuccessful() || response == null) {
            return null;
        }
        body = response.body();
        inputStream = ContentLengthInputStream.obtain(body.byteStream(), body.contentLength());
        return inputStream;

    }


    @Override
    public void cleanup() {

        try {
            if (inputStream != null) {
                inputStream.close();
            }
            if (body != null) {
                body.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    public String getId() {
        return url.getCacheKey();
    }

    @Override
    public void cancel() {
        isCancelled = true;
    }
}
